import {Avatar, Icon, Menu, Spin, Form, Row, Modal, Input, message} from 'antd';
import {FormattedMessage} from 'umi-plugin-react/locale';
import React from 'react';
import {connect} from 'dva';
import router from 'umi/router';
import HeaderDropdown from '../HeaderDropdown';
import styles from './index.less';
import APP from '@/components/Tool/BaseAPP';
const { confirm } = Modal;

let checkUserInterval = null;

@connect(({ userModel }) => ({  // 连接usermanage.js文件
    userModel,
}))
class AvatarDropdown extends React.Component {
    state = {
        loading:false,
        isShowEditPwdModal: false
    };
    onMenuClick = (currentUser, event) => {
        const {key} = event;

        if (key === 'logout') {
            const {dispatch} = this.props;

            if (dispatch) {
                dispatch({
                    type: 'login/logout',
                });
            }

            return;
        } else if (key === 'editPwd') {
            this.setState({
                isShowEditPwdModal:true
            });
            return;
        }

        router.push({
            pathname: `/account/${key}`,
            state: {id: currentUser.id}
        });
    };

    render() {
        const {
            currentUser = {
                avatar: '',
                name: '',
            },
            menu,
        } = this.props;
        this.checkUser();
        const menuHeaderDropdown = (
            <Menu className={styles.menu} selectedKeys={[]} onClick={(event) => this.onMenuClick(currentUser, event)}>
                {menu && (
                    <Menu.Item key="center">
                        <Icon type="user"/>
                        <FormattedMessage id="menu.account.center" defaultMessage="account center"/>
                    </Menu.Item>
                )}

                {/*{menu && (
                    <Menu.Item key="settings">
                        <Icon type="setting" />
                        <FormattedMessage id="menu.account.settings" defaultMessage="account settings" />
                    </Menu.Item>
                )}*/}

                {menu && <Menu.Divider/>}

                {menu && (
                    <Menu.Item key="editPwd">
                        <Icon type="setting"/>
                        <FormattedMessage id="menu.account.editPwd" defaultMessage="reset password"/>
                    </Menu.Item>
                )}

                {menu && <Menu.Divider/>}

                <Menu.Item key="logout">
                    <Icon type="logout"/>
                    <FormattedMessage id="menu.account.logout" defaultMessage="logout"/>
                </Menu.Item>
            </Menu>
        );
        return currentUser && currentUser.userName ? (
            <HeaderDropdown overlay={menuHeaderDropdown}>
                <span className={`${styles.action} ${styles.account}`}>
                    <Avatar size="small" className={styles.avatar} src={currentUser.avatar} alt="avatar"/>
                    <span className={styles.name}>{currentUser.userName}</span>
                    <EditPwdForm parent={this}/>
                </span>
            </HeaderDropdown>
        ) : (
            <Spin
                size="small"
                style={{
                    marginLeft: 8,
                    marginRight: 8,
                }}
            />
        );
    }

    checkUserDispatch() {
        const {dispatch} = this.props;
        dispatch({
            type: 'userModel/checkUser',
            payload: {},
            callback: function(data) {
                if (!data.success) {
                    clearInterval(checkUserInterval);
                    dispatch({
                        type: 'login/logout',
                    });
                }
            }
        });
    }

    checkUser() {
        const that = this;
        function whileDispatch() {
            const token = sessionStorage.getItem('MYRCIB_USER_TOKEN');
            if (token) {
                that.checkUserDispatch();
            } else {
                clearInterval(checkUserInterval);
            }
        }
        if (checkUserInterval == null) {
            that.checkUserDispatch();
            const timeout = 1000 * 60 * 10;
            checkUserInterval = setInterval(whileDispatch, timeout);
        }
    }
}

const EditPwdForm = Form.create()(props => {
    let {parent, form} = props;
    const {dispatch} = parent.props;
    const {loading, isShowEditPwdModal} = parent.state;
    const {getFieldDecorator} = form;
    const formItemLayout = {
        style: {
            margin: '0px',
        },
    };

    //-- 显示/隐藏 数据编辑窗口
    function handlerEditModal() {
        form.resetFields();
        let {isShowEditPwdModal} = parent.state;
        isShowEditPwdModal = !isShowEditPwdModal;
        parent.setState({isShowEditPwdModal});
    }

    function submit() {
        form.validateFields((err, values) => {
            if (err) return;
            APP.validNilParams(values);
            if (!/^[A-Za-z\d]{8,20}$/.test(values.passWord)) {
                message.error('请输入8-20个字符的新密码');
                return;
            }
            parent.setState({loading: true});
            dispatch({
                type: 'userModel/editpwd',
                payload: values,
                callback: function (data) {
                    parent.setState({loading: false});
                    if (data.success) {
                        confirm({
                            title:'修改密码成功',
                            content:'修改密码成功，要退出从新登录吗？',
                            onOk() {
                                dispatch({
                                    type: 'login/logout',
                                });
                            },
                            onCancel() {
                                handlerEditModal();
                            },
                        });
                    } else {
                        message.error(data.msg);
                    }
                }
            });
        });
    }

    return(
        <Modal
            title={'修改密码'}
            visible={isShowEditPwdModal}
            onOk={() => submit()}
            onCancel={() => handlerEditModal()}
            okText="保存"
            cancelText='返回'
            confirmLoading={loading}
        >
            <Form layout="vertical">
                <Row>
                    <Form.Item {...formItemLayout}>
                        {getFieldDecorator('oldPwd', {
                            initialValue: '',
                            rules: [
                                {
                                    required: true,
                                    message: '请输入旧密码',
                                },
                            ],
                        })(<Input placeholder={"请输入旧密码"} allowClear={true} type={'password'}/>)}
                    </Form.Item>
                </Row>
                <Row>
                    <Form.Item {...formItemLayout}>
                        {getFieldDecorator('passWord', {
                            initialValue: '',
                            rules: [
                                {
                                    required: true,
                                    message: '请输入新密码',
                                },
                            ],
                        })(<Input placeholder={"请输入新密码"} allowClear={true} type={'password'}/>)}
                    </Form.Item>
                </Row>
            </Form>
        </Modal>
    );
});

export default connect(({user}) => ({
    currentUser: user.currentUser,
}))(AvatarDropdown);
